package com.tutu.sys.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.PredicateUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tutu.common.GlobalConstants;
import com.tutu.common.GlobalConstants.ISessionMessageSetting;
import com.tutu.common.util.DatatablesJson;
import com.tutu.common.util.JsonReturnObject;
import com.tutu.common.util.LogAction;
import com.tutu.common.util.SysAuditModelType;
import com.tutu.sys.entity.SysFile;
import com.tutu.sys.entity.SysMsgInstation;
import com.tutu.sys.entity.SysMsgUser;
import com.tutu.sys.service.ISysFileService;
import com.tutu.sys.service.ISysMsgService;
import com.tutu.user.entity.SysUser;
import com.tutu.user.service.ISysUserService;

@Controller
@RequestMapping("/msg")
@LogAction(ownermodel=SysAuditModelType.MESSAGE_MANAGEMENT)
public class MsgAction {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private ISysMsgService sysMsgService;
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ISysFileService sysFileService;
	
	@RequestMapping(value="/queryMyMsg")
	public String queryMyMsg(){
		return "system/queryMyMsg";
	}
	
	@RequestMapping("/getMyMsgs")
	@ResponseBody
	public JsonReturnObject<DatatablesJson<SysMsgUser>> getMyMsgs(@RequestParam String sEcho, @RequestParam int iDisplayStart,@RequestParam int iDisplayLength,@RequestParam(required=false) String sSearch){
		JsonReturnObject<DatatablesJson<SysMsgUser>> jsonReturnObject = new JsonReturnObject<DatatablesJson<SysMsgUser>>(false,"获取消息失败");
		PageHelper.startPage((iDisplayStart/iDisplayLength)+1, iDisplayLength);
		try {
			SysMsgUser sysMsgUser = new SysMsgUser();
			sysMsgUser.setReceiver(GlobalConstants.getCurrentUser().getUserId());
			sysMsgUser.setAliveFlag(GlobalConstants.FLAG_ENABLE);
			if(StringUtils.isNotBlank(sSearch)){
				SysMsgInstation sysMsgInstation = new SysMsgInstation();
				sysMsgInstation.setTitle(sSearch);
				sysMsgUser.setSysMsgInstation(sysMsgInstation);
			}
			List<SysMsgUser> sysMsgUsers = this.sysMsgService.getMyMsgs(sysMsgUser);
			DatatablesJson<SysMsgUser> datatablesJson = new DatatablesJson<SysMsgUser>();
			datatablesJson.setEcho(sEcho);
			PageInfo<SysMsgUser> pageInfo = new PageInfo<SysMsgUser>(sysMsgUsers);
			datatablesJson.setTotalRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setTotalDisplayRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setData(pageInfo.getList());
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject(datatablesJson);
		} catch (Exception e) {
			logger.error("获取用户消息", e);
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/showMyMsgInfo")
	public String showMyMsgInfo(@RequestParam String userMsgId, Model model){
		SysMsgUser sysMsgUser = sysMsgService.getSysMsgUser(userMsgId);
		if(!sysMsgUser.getIsView()){
			Calendar calendar = Calendar.getInstance();
			sysMsgUser.setViewDate(calendar.getTime());
			sysMsgUser.setModifier(GlobalConstants.getCurrentUser().getUserId());
			sysMsgUser.setModifyTime(calendar.getTime());
			this.sysMsgService.updateSysMsgUser(sysMsgUser);
		}
		model.addAttribute("sysMsgUser", sysMsgUser);
		List<SysFile> sysFiles = new ArrayList<SysFile>();
		if(StringUtils.isNotEmpty(sysMsgUser.getSysMsgInstation().getAdjunct())){
			List<String> fileIds = Arrays.asList(sysMsgUser.getSysMsgInstation().getAdjunct().split(","));
			sysFiles = this.sysFileService.getSysFiles(fileIds);
		}
		model.addAttribute("sysFiles", sysFiles);
		return "system/showMyMsgInfo";
	}
	
	@RequestMapping(value="/querySent")
	public String querySent() {
		return "system/querySent";
	}
	
	@RequestMapping("/getSendMsgs")
	@ResponseBody
	public JsonReturnObject<DatatablesJson<SysMsgInstation>> getSendMsgs(@RequestParam String sEcho, @RequestParam int iDisplayStart,@RequestParam int iDisplayLength,@RequestParam(required=false) String sSearch){
		JsonReturnObject<DatatablesJson<SysMsgInstation>> jsonReturnObject = new JsonReturnObject<DatatablesJson<SysMsgInstation>>(false,"获取已发消息失败");
		Page<SysMsgInstation> page = new Page<SysMsgInstation>((iDisplayStart/iDisplayLength)+1, iDisplayLength);
		try {
			SysMsgInstation sysMsgInstation = new SysMsgInstation();
			sysMsgInstation.setSender(GlobalConstants.getCurrentUser().getUserId());
			sysMsgInstation.setAliveFlag(GlobalConstants.FLAG_ENABLE);
			if(StringUtils.isNotBlank(sSearch))
				sysMsgInstation.setTitle(sSearch);
			List<SysMsgInstation> sysMsgInstations = this.sysMsgService.getMySendMsg(sysMsgInstation, page);
			DatatablesJson<SysMsgInstation> datatablesJson = new DatatablesJson<SysMsgInstation>();
			datatablesJson.setEcho(sEcho);
			PageInfo<SysMsgInstation> pageInfo = new PageInfo<SysMsgInstation>(sysMsgInstations);
			datatablesJson.setTotalRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setTotalDisplayRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setData(pageInfo.getList());
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject(datatablesJson);
		} catch (Exception e) {
			logger.error("获取已发消息", e);
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/showSendMsgInfo")
	public String showSendMsgInfo(@RequestParam String msgId, Model model){
		SysMsgInstation sysMsgInstation = sysMsgService.getSysMsgInstationById(msgId);
		model.addAttribute("sysMsgInstation", sysMsgInstation);
		List<SysFile> sysFiles = new ArrayList<SysFile>();
		if(StringUtils.isNotEmpty(sysMsgInstation.getAdjunct())){
			List<String> fileIds = Arrays.asList(sysMsgInstation.getAdjunct().split(","));
			sysFiles = this.sysFileService.getSysFiles(fileIds);
		}
		model.addAttribute("sysFiles", sysFiles);
		return "system/showSendMsgInfo";
	}
	
	/**
	 * 发送消息
	 * @return
	 */
	@RequestMapping(value="/createSysMsg")
	public String createSysMsg(Model model) {
		SysUser sysUser = new SysUser();
		sysUser.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		List<SysUser> sysUsers = this.sysUserService.getUsers(sysUser);
		model.addAttribute("sysUsers", sysUsers);
		return "system/createSysMsg";
	}

	@RequestMapping("/saveSysMsg")
	@LogAction(description="发送消息",operateType="发送消息")
	public String saveSysMsg(HttpSession session, @RequestParam(required=false) MultipartFile[] files, @ModelAttribute("sysMsgFrom") SysMsgInstation sysMsgInstation, @RequestParam String receivers){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "发送消息失败", "发送消息成功");
		Calendar calendar = Calendar.getInstance();
		ResourceBundle resourceBundle = ResourceBundle.getBundle("common");
		sysMsgInstation.setSender(GlobalConstants.getCurrentUser().getUserId());
		sysMsgInstation.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		sysMsgInstation.setCreator(GlobalConstants.getCurrentUser().getUserId());
		sysMsgInstation.setCreateTime(Calendar.getInstance().getTime());
		try{
			List<String> adjuncts = new ArrayList<String>();
			String fileStorePath = resourceBundle.getString(GlobalConstants.FILE_STORE_PATH);
			if(!fileStorePath.endsWith(File.separator)){
				fileStorePath += File.separator;
			}
			for(MultipartFile multipartFile : files){
				if(StringUtils.isNotBlank(multipartFile.getOriginalFilename())){
					File dirFile = FileUtils.getFile(fileStorePath+SysFile.MSG_FILE_PATH+File.separator);
					if(!dirFile.exists()){
						dirFile.mkdirs();
					}
					String storeFileName = StringUtils.substringBeforeLast(multipartFile.getOriginalFilename(), ".")+DateFormatUtils.format(calendar, "yyyyMMddHHmmss")+RandomStringUtils.randomAlphanumeric(3)+"."+StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), ".");
					File file = FileUtils.getFile(fileStorePath+SysFile.MSG_FILE_PATH+File.separator+storeFileName);
					file.createNewFile();
					multipartFile.transferTo(file);
					
					SysFile sysFile = new SysFile();
					sysFile.setFileName(multipartFile.getOriginalFilename());
					sysFile.setFileType(multipartFile.getContentType());
					sysFile.setFileSize(multipartFile.getSize());
					sysFile.setFilePath(SysFile.MSG_FILE_PATH+File.separator+storeFileName);
					sysFile.setAliveFlag(GlobalConstants.FLAG_ENABLE);
					sysFile.setCreator(GlobalConstants.getCurrentUser().getUserId());
					sysFile.setCreateTime(calendar.getTime());
					sysFileService.saveSysFile(sysFile);
					adjuncts.add(sysFile.getFileId());
				}
			}
			sysMsgInstation.setAdjunct(StringUtils.join(adjuncts, ","));
			
			if(StringUtils.isNotBlank(receivers)){
				final Set<String> recerverSet = new HashSet<String>(Arrays.asList(receivers.split(",")));
				final String title = sysMsgInstation.getTitle();
				final String content = StringUtils.isEmpty(sysMsgInstation.getContent())?"":StringUtils.abbreviate(sysMsgInstation.getContent(), 16);
				this.sysMsgService.saveSysMsg(sysMsgInstation, recerverSet);
				sessionMessageSetting.setIsSuccess(true);
				
				ServerContext serverContext = ServerContextFactory.get();
				Browser.withAllSessionsFiltered(serverContext, new ScriptSessionFilter() {
					
					@Override
					public boolean match(ScriptSession scriptSession) {
						String userId = (String) scriptSession.getAttribute(GlobalConstants.SESSION_USER_INFO);
						
						if(StringUtils.isNotEmpty(userId) && CollectionUtils.exists(recerverSet, PredicateUtils.equalPredicate(userId))){
							return true;
						}
						return false;
					}
				}, new Runnable() {
					private ScriptBuffer scriptBuffer = new ScriptBuffer();
					
					@Override
					public void run() {
						String callFunction = "updateUserMsg";
						scriptBuffer.appendCall(callFunction, "1", title, content);
						Collection<ScriptSession> scriptSessions = Browser.getTargetSessions();
						for(ScriptSession scriptSession : scriptSessions){
							scriptSession.addScript(scriptBuffer);
						}
					}
				});
			}
		}catch(Exception e){
			logger.error("发送消息", e);
		}
		return "redirect:/msg/querySent.do";
	}
}
